package myJs.user

import myJs.Utils._
import myJs.Implicits._

import myJs.myPkg._
import myJs.myPkg.jquery._
import myJs.user.SampleSnpDetail.str2SnpReadsDatas
import org.scalajs.dom._
import org.scalajs.dom.ext.Ajax
import scalatags.Text.TypedTag
import scalatags.Text.all._
import shared.Pojo.{ReadsData, SeqData, SnpReadsData, StrReadsData}
import shared.VarTool
import shared.plotly.{Pie, Scatter}
import shared.plotly.element.Color.StringColor
import shared.plotly.element.ScatterMode.{Lines, Markers, Text}
import shared.plotly.element.{Anchor, AxisType, HoverInfo, Line, Marker, ScatterMode, TextFont}
import shared.plotly.layout.HoverMode.Closest
import shared.plotly.layout.Ref.{XRef, YRef}
import shared.plotly.layout.{Axis, Font, Layout, Legend, Margin, Shape}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.scalajs.js
import scala.scalajs.js.JSON
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import myJs.Implicits._
import myJs.user.SampleDetail._
import argonaut._
import Argonaut._
import myJs.Codecs._
import myJs.myPkg.bootstrap.Bootstrap.default._
import myJs.tool.Tool
import shared.highcharts.config.{Chart, Credits, HighchartsConfig, SeriesAny, SeriesVennData, Title, Venn}

import scala.scalajs.js.JSConverters._
import scala.collection.SeqMap
import scala.scalajs.js.Dynamic.{global => g}

/**
 * Created by yz on 2019/4/25
 */
@JSExportTopLevel("CompareMissionDetail")
object CompareMissionDetail {

  val typeTagEmpty = List[TypedTag[String]]()
  val kind = VarTool.compareMissionStr

  case class SampleData(sampleData: JArJDS, sampleName: String)

  @JSExport("init")
  def init = {
    refreshIdSelect
    initStrTable
    initSnpDetailTable
  }

  def highchartsTest = {

    //    val barChartConfig = HighchartsConfig(
    //      chart = Chart(`type` = "bar"),
    //      title = Title(text = "Demo bar chart"),
    //      yAxis = YAxis(title = YAxisTitle(text = "Fruit eaten")),
    //      xAxis = XAxis(categories = Seq("Apples", "Bananas", "Oranges")),
    //      series = Seq(
    //        SeriesBar(name = "Jane", data = List[Double](1, 0, 4)),
    //        SeriesBar(name = "John", data = List[Double](5, 7, 3))
    //      )
    //    )
    //
    //    myHighcharts.chart($("#container"), barChartConfig)

  }

  def highchartVennPlot(tmpData: js.Any, divId: String) = {
    val data = tmpData.toJDJAn
    val ids = data("each").toJArJDJAn.map(_.myGet("id")).toList
    val interVennData = SeriesVennData(
      sets = ids,
      value = data.myGetDouble("inter"),
      name = s"Intersect<br>${data("inter")}"
    )
    val datas = data("each").toJArJDJAn.toList.map { dict =>
      SeriesVennData(
        sets = List(dict.myGet("id")),
        value = dict.myGet("num").toDouble,
        name = s"${dict("id")}<br>${dict("num")}"
      )
    } ::: List(interVennData)
    val series = Seq(
      Venn(name = "", data = datas),
    )
    val chartConfig = HighchartsConfig(
      chart = Chart(`type` = "venn"),
      title = Title(text = ""),
      series = series,
      credits = Credits(enabled = false)
    )
    myHighcharts.chart(divId, chartConfig)
  }

  def refreshIdSelect = {
    val inputName = "id"
    val url = g.jsRoutes.controllers.MissionController.getAllMission().url.toString
    Ajax.get(url = s"${url}?kind=${kind}").map { xhr =>
      val data = JSON.parse(xhr.responseText).toJArJDS
      val array = data.filter(_ ("state") == "success").map { dict =>
        js.Dictionary("text" -> dict("missionName"), "id" -> dict("id"))
      }
      val options = Select2Options.dictData(array)
      Tool.getInputByName(inputName).select2(options)
      Tool.getInputByName(inputName).`val`(getId).select2().trigger("onchange")
    }
  }

  def initStrTable = {
    val map = SeqMap(
      "genotype" -> "Allele Name",
      "typedAllele" -> "Typed Allele",
      "reads" -> "Reads",
      "repeatSeq" -> "Repeat Sequence"
    )
    val columnNames = map.keys.toJSArray
    val columns = columnNames.map { columnName =>
      val title = map.getOrElse(columnName, columnName)
      ColumnOptions.field(columnName).title(title).sortable(true)
    }
    val options = TableOptions.columns(columns)
    List("sample1", "sample2").foreach { sampleId =>
      $(s"#locusModal #${sampleId} #detailTable").bootstrapTable(options)
    }
  }

  @JSExport("idChange")
  def idChange(y: Element) = {
    val myValue = $(y).find(">option:selected").`val`().toString
    idChangeByValue(myValue)
  }

  def getReadsData(missionId: String) = {
    val url = g.jsRoutes.controllers.SampleController.getCompareReadsData().url.toString
    Ajax.get(url = s"${url}?missionId=${missionId}").map { xhr =>
      xhr.responseText.toJArJDJAn
    }
  }

  def getDiffReadsData(missionId: String) = {
    val url = g.jsRoutes.controllers.SampleController.getCompareDiffReadsData().url.toString
    Ajax.get(url = s"${url}?missionId=${missionId}").map { xhr =>
      xhr.responseText.toJArJDJAn
    }
  }

  def getSnpReadsData(idStr: String) = {
    val url = g.jsRoutes.controllers.SampleController.getCompareSnpReadsData().url.toString
    Ajax.get(url = s"${url}?missionId=${idStr}").map { xhr =>
      xhr.responseText.toJArJDJAn
    }
  }

  def getVennData(idStr: String) = {
    val url = g.jsRoutes.controllers.SampleController.getCompareVennData().url.toString
    Ajax.get(url = s"${url}?missionId=${idStr}").map { xhr =>
      xhr.responseText.toJDJAn
    }
  }

  def getDiffSnpReadsData(missionId: String) = {
    val url = g.jsRoutes.controllers.SampleController.getCompareDiffSnpReadsData().url.toString
    Ajax.get(url = s"${url}?missionId=${missionId}").map { xhr =>
      xhr.responseText.toJArJDJAn
    }
  }

  def getCompareRawSeqData(idStr: String) = {
    val url = g.jsRoutes.controllers.SampleController.getCompareRawSeqData().url.toString
    Ajax.get(url = s"${url}?missionId=${idStr}").map { xhr =>
      xhr.responseText.toJArJDS
    }
  }

  def getCompareRawSnpSeqData(idStr: String) = {
    val url = g.jsRoutes.controllers.SampleController.getCompareRawSnpSeqData().url.toString
    Ajax.get(url = s"${url}?missionId=${idStr}").map { xhr =>
      xhr.responseText.toJArJDS
    }
  }

  def getSeqDatas(rs: String) = {
    rs.decodeOption[List[SeqData]].getOrElse(Nil)
  }

  @JSExport("strDetailShow")
  def strDetailShow(str: String) = {
    val seqDatas = getSeqDatas(str)
    val locus = seqDatas.head.locus
    val modalId = "locusModal"
    $(".locus").text(locus)
    val array = JSON.parse(str).toJArJDS
    val ids = array.map(_ ("id")).distinct
    val sample1Name = ids(0)
    val sample2Name = ids(1)
    val sample1Data = array.filter(_ ("id") == sample1Name)
    val sample2Data = array.filter(_ ("id") == sample2Name)
    val map = SeqMap("sample1" -> SampleData(sample1Data, sample1Name), "sample2" -> SampleData(sample2Data, sample2Name))
    map.foreach { case (sampleId, data) =>
      val sampleData = data.sampleData
      val sampleName = data.sampleName
      Tool.refreshTable(sampleData, $(s"#${modalId} #${sampleId} #detailTable"))
      strDetailPlot(sampleData, $(s"#${modalId} #${sampleId} #strDetailChart"))
      $(s"#${modalId} #${sampleId} #sampleName").text(sampleName)
    }
    jQuery(s"#${modalId}").modal("show")
  }

  def strDetailPlot(strSeqDatas: js.Array[js.Dictionary[String]], jq: JQuery) = {
    val step = 0.25
    val ids = strSeqDatas.map(_ ("id")).distinct
    val map = ids.map { id =>
      val eachData = strSeqDatas.filter(_ ("id") == id)
      val genotypes = eachData.map(_ ("genotype"))
      val xs = genotypes.indices.toList
      (xs).zip(genotypes).toSeqMap
    }.reduceLeft((x, y) => x ++ y)
    val plotData = ids.toList.map { id =>
      val eachData = strSeqDatas.filter(_ ("id") == id)
      val genotypes = eachData.map(_ ("genotype"))
      val xs = genotypes.indices.toList
      val reads = eachData.map(_ ("reads"))
      val xMap = xs.map(_.toDouble).zip(reads).toMap
      val genotypeMap = xs.map(_.toDouble).zip(genotypes).toMap
      val linesX = (BigDecimal(xs.min - 0.5) to BigDecimal(xs.max + 0.5) by BigDecimal(step)).toList.map(_.toDouble)
      val linesY = linesX.map { x =>
        xMap.getOrElse(x, "0")
      }
      val texts = linesX.map { case x =>
        if (xMap.isDefinedAt(x)) {
          val genotype = genotypeMap(x)
          val read = xMap(x)
          s"Allele Name:${genotype}<br>Reads:${read}"
        } else ""

      }
      Scatter(
        values = linesX,
        secondValues = linesY,
        marker = Marker(
        ),
        hoverinfo = HoverInfo.Text,
        mode = ScatterMode(Lines),
        text = texts,
        name = id
      )
    }

    val layout = Layout(
      title = s"",
      xaxis = Axis(
        title = s"",
        `type` = AxisType.Linear,
        tickangle = 0.0,
        tickvals = map.keys.toList,
        ticktext = map.values.toList,
        autorange = true,
        tickfont = Font(size = 10),
        zeroline = false
      ),
      yaxis = Axis(
        title = s"Number of reads",
        autorange = true,
      ),
      margin = Margin(b = 20,
        t = 20,
        r = 0),
      width = 400,
      height = 300,
      hovermode = Closest,
      dragmode = false
    )
    val config = PlotlyConfigOptions.displayModeBar(false)
    myPlotly.newPlot(jq, plotData, layout, config)
  }

  def fillReadsData(array: JArJDJAn, seqDatas: JArJDS, jq: JQuery) = {
    val first1Height = 30
    val diffNum = array.map { dict =>
      dict.myGet("locus")
    }.distinct.size
    $("#strDiffData #diffNum").text(diffNum.toString)
    val html = array.map { dict =>
      val key = dict.myGet("locus")
      val sample1Genotypes = dict("sample1").toJArS
      val sample2Genotypes = dict("sample2").toJArS
      val myBackgroundColor = "#FABD82"
      val seqDataRow = seqDatas.filter(_ ("locus") == key)
      val sample1ColSpan = if (sample1Genotypes.size == 1) 2 else 1
      val sample1Width = if (sample1Genotypes.size == 1) "100%" else "50%"
      val sample2ColSpan = if (sample2Genotypes.size == 1) 2 else 1
      val sample2Width = if (sample2Genotypes.size == 1) "100%" else "50%"
      div(cls := "form-group", marginRight := 15, height := 80, marginBottom := 20,
        table(cls := " table table-bordered strTable", width := 150,
          tr(height := first1Height, maxHeight := first1Height, minHeight := first1Height,
            td(colspan := 2, `class` := "myTd", color := "#FFFFFF",
              a(key, `class` := "myA", cursor := "pointer",
                onclick := s"CompareMissionDetail.strDetailShow('${JSON.stringify(seqDataRow)}')"),
              fontWeight := "bold", backgroundColor := "#5E738B", paddingTop := 3, paddingBottom := 3)
          ),
          tr(height := first1Height, maxHeight := first1Height, minHeight := first1Height,
            sample1Genotypes.zipWithIndex.toList.map { case (inData, i) =>
              val sample2Genotype = if (sample2Genotypes.size >= i + 1) sample2Genotypes(i) else ""
              val bgColor = if (inData != sample2Genotype || sample1Genotypes.size != sample2Genotypes.size) {
                myBackgroundColor
              } else ""
              td(inData, backgroundColor := bgColor, width := sample1Width, paddingTop := 3, paddingBottom := 3, colspan := sample1ColSpan)
            }
          ),
          tr(height := first1Height, maxHeight := first1Height, minHeight := first1Height,
            sample2Genotypes.toList.map { inData =>
              td(inData, width := sample2Width, fontSize := "12px", paddingTop := 3, paddingBottom := 3, colspan := sample2ColSpan)
            }
          )
        )
      )
    }.mkString("&nbsp;")
    jq.html(html)
  }


  //  def highchartVennPlot(tmpData: js.Any, divId: String) = {
  //    val data = tmpData.toJDJAn
  //    val ids = data("each").toJArJDJAn.map(_ ("id"))
  //    val interDict = js.Dictionary(
  //      "sets" -> ids,
  //      "value" -> data("inter"),
  //      "name" -> s"Intersect<br>${data("inter")}",
  //    )
  //    val dataDict = data("each").toJArJDJAn.map { dict =>
  //      js.Dictionary(
  //        "sets" -> js.Array(dict("id")),
  //        "value" -> dict("num"),
  //        "name" -> s"${dict("id")}<br>${dict("num")}",
  //      )
  //    } ++ js.Array((interDict))
  //    val dict = js.Dictionary(
  //      "series" -> js.Array(
  //        js.Dictionary(
  //          "type" -> "venn",
  //          "name" -> "",
  //          "data" -> dataDict,
  //        )
  //      ),
  //      "title" -> js.Dictionary(
  //        "text" -> ""
  //      ),
  //      "credits" -> js.Dictionary(
  //        "enabled" -> false
  //      ),
  //
  //    )
  //    g.venn(divId, dict)
  //  }

  def idChangeByValue(myValue: String) = {
    val id = myValue
    val index = layer.load(1, Tool.layerOptions.shade(js.Array("0.1", "#fff")))
    val strPlotF = getReadsData(id).map { filterDatas =>
      scatterPlot(filterDatas, $(s"#str #scatterChart"))
    }
    val snpPlotF = getSnpReadsData(id).map { filterDatas =>
      snpScatterPlot(filterDatas, $(s"#snp #scatterChart"))
    }
    val vennPlotF = getVennData(id).map { data =>
      highchartVennPlot(data("total"), "totalContainer")
      highchartVennPlot(data("str"), "strContainer")
      highchartVennPlot(data("snp"), "snpContainer")
    }
    val fillReadsDataF = getDiffReadsData(id).zip(getCompareRawSeqData(id)).map { case (filterDatas, seqDatas) =>
      fillReadsData(filterDatas, seqDatas, $(s"#strDiffData #data"))
    }
    val fillSnpReadsDataF = getDiffSnpReadsData(id).zip(getCompareRawSnpSeqData(id)).map { case (filterDatas, seqDatas) =>
      fillSnpReadsData(filterDatas, seqDatas, $(s"#snpDiffData #data"))
    }
    refreshMissionInfo(id).zip(strPlotF).zip(snpPlotF).zip(vennPlotF).zip(fillReadsDataF).zip(fillSnpReadsDataF).map { x =>
      layer.close(index)
    }
  }

  def getCompareSnpReadsData(idStr: String) = {
    val url = g.jsRoutes.controllers.SampleController.getCompareSnpReadsData().url.toString
    Ajax.get(url = s"${url}?missionId=${idStr}").map { xhr =>
      xhr.responseText.toJArJDJAn
    }
  }

  def initSnpDetailTable = {
    val map = SeqMap(
      "genotype" -> "Allele Name",
      "typedAllele" -> "Typed Allele",
      "reads" -> "Reads"
    )
    val columnNames = map.keys.toJSArray
    val columns = columnNames.map { columnName =>
      val title = map.getOrElse(columnName, columnName)
      ColumnOptions.field(columnName).title(title).sortable(true)
    }
    val options = TableOptions.columns(columns)
    List("sample1", "sample2").foreach { sampleId =>
      $(s"#snpModal #${sampleId} #detailTable").bootstrapTable(options)
    }
  }

  @JSExport("snpDetailShow")
  def snpDetailShow(str: String) = {
    val seqDatas = getSeqDatas(str)
    val locus = seqDatas.head.locus
    $(".locus").text(locus)
    val modalId = "snpModal"
    val array = JSON.parse(str).toJArJDS
    val ids = array.map(_ ("id")).distinct
    val sample1Name = ids(0)
    val sample2Name = ids(1)
    val sample1Data = array.filter(_ ("id") == ids(0))
    val sample2Data = array.filter(_ ("id") == ids(1))
    val map = SeqMap("sample1" -> SampleData(sample1Data, sample1Name), "sample2" -> SampleData(sample2Data, sample2Name))
    map.foreach { case (sampleId, data) =>
      val sampleData = data.sampleData
      val sampleName = data.sampleName
      Tool.refreshTable(sampleData, $(s"#${modalId} #${sampleId} #detailTable"))
      snpDetailPlot(sampleData, $(s"#snpModal #${sampleId} #detailChart"))
      $(s"#${modalId} #${sampleId} #sampleName").text(sampleName)
    }
    jQuery(s"#${modalId}").modal("show")
  }

  def snpDetailPlot(seqDatas: JArJDS, jq: JQuery) = {
    val xs = seqDatas.map(_ ("genotype")).toList
    val reads = seqDatas.map(_ ("reads")).toList
    val plotData = Seq(
      Pie(
        labels = xs,
        values = reads,
        marker = Marker(
        ),
        hoverinfo = HoverInfo.Y,
        width = 0.5
      )
    )

    val layout = Layout(
      title = s"",
      xaxis = Axis(
        title = s"",
        `type` = AxisType.Category,
        tickangle = 0.0,
        autorange = true,
        tickfont = Font(size = 10)
      ),
      yaxis = Axis(
        title = s"Number of reads",
        autorange = true
      ),
      margin = Margin(b = 0,
        t = 0,
        l = 0,
        r = 0),
      width = 400,
      height = 400,
      hovermode = Closest,
      dragmode = false
    )
    val config = PlotlyConfigOptions.displayModeBar(false)
    myPlotly.newPlot(jq, plotData, layout, config)
  }


  def fillSnpReadsData(array: JArJDJAn, seqDatas: JArJDS, jq: JQuery) = {
    val first1Height = 30
    val diffNum = array.map { dict =>
      dict.myGet("locus")
    }.distinct.size
    val myBackgroundColor = "#FABD82"
    $("#snpDiffData #diffNum").text(diffNum.toString)
    val html = array.map { dict =>
      val key = dict.myGet("locus")
      val seqDataRow = seqDatas.filter(_ ("locus") == key)
      val sample1Genotypes = dict("sample1").toJArS
      val sample2Genotypes = dict("sample2").toJArS
      val sample1ColSpan = if (sample1Genotypes.size == 1) 2 else 1
      val sample2ColSpan = if (sample2Genotypes.size == 1) 2 else 1
      div(cls := "form-group", marginRight := 15, height := 80, marginBottom := 20,
        table(cls := " table table-bordered strTable", width := 150,
          tr(height := first1Height, maxHeight := first1Height, minHeight := first1Height,
            td(colspan := 2,
              a(key, color := "#FFFFFF", onclick := s"CompareMissionDetail.snpDetailShow('${JSON.stringify(seqDataRow)}')"),
              fontWeight := "bold", backgroundColor := "#5E738B", paddingTop := 3, paddingBottom := 3)
          ),
          tr(height := first1Height, maxHeight := first1Height, minHeight := first1Height,
            sample1Genotypes.zipWithIndex.toList.map { case (inData, i) =>
              val sample2Genotype = if (sample2Genotypes.size >= i + 1) sample2Genotypes(i) else ""
              val colStr = Tool.getGenotypeCol(inData)
              val bgColor = if (inData != sample2Genotype || sample1Genotypes.size != sample2Genotypes.size) {
                myBackgroundColor
              } else ""
              td(inData, backgroundColor := bgColor, color := colStr, width := "50%", paddingTop := 3,
                paddingBottom := 3, colspan := sample1ColSpan)
            }),
          tr(height := first1Height, maxHeight := first1Height, minHeight := first1Height,
            sample2Genotypes.zipWithIndex.toList.map { case (inData, i) =>
              td(inData, colspan := sample2ColSpan, fontSize := "12px", paddingTop := 3, paddingBottom := 3)
            }
          )
        )
      )
    }.mkString("&nbsp;")
    jq.html(html)
  }


  def scatterPlot(array: JArJDJAn, jq: JQuery) = {
    val traces = array.map {
      dict =>
        val datas = SampleDetail.getStrReadsDatas(JSON.stringify(dict("data")))
        val id = dict("id").toString
        val xs = datas.map(_.productSize)
        val reads = datas.map(_.reads)
        val texts = datas.map {
          x =>
            s"Locus:${
              x.locus
            }<br>Allele Name:${
              x.genotype
            }<br>Length(bp):${
              x.productSize
            }<br>Depth:${
              x.reads
            }"
        }
        Scatter(
          values = xs,
          secondValues = reads,
          marker = Marker(
          ),
          mode = ScatterMode(Markers),
          hoverinfo = HoverInfo.Text,
          text = texts,
          name = id
        )
    }
    val plotData = traces.toList

    val layout = Layout(
      title = s"",
      xaxis = Axis(
        title = s"Length(bp)",
        `type` = AxisType.Linear,
        tickangle = 0.0,
        autorange = true,
        tickfont = Font(size = 10)
      ),
      yaxis = Axis(
        title = s"Number of reads",
        autorange = true
      ),
      margin = Margin(b = 40, l = 80, t = 0, r = 0),
      hovermode = Closest,
      width = 700,
      height = 500,
      dragmode = false,
      legend = Legend(
        xanchor = Anchor.Right,
        x = 1.0,
        y = 1.0
      )
    )
    val config = PlotlyConfigOptions.displayModeBar(false)
    myPlotly.newPlot(jq, plotData, layout, config)
  }

  def snpScatterPlot(array: JArJDJAn, jq: JQuery) = {
    val traces = array.map {
      dict =>
        val datas = SampleSnpDetail.str2SnpReadsDatas(JSON.stringify(dict("data")))
        val id = dict("id").toString
        val xs = datas.map(_.productSize)
        val reads = datas.map(_.reads)
        val texts = datas.map {
          x =>
            s"Locus:${
              x.locus
            }<br>Allele Name:${
              x.genotype
            }<br>Length(bp):${
              x.productSize
            }<br>Depth:${
              x.reads
            }"
        }
        Scatter(
          values = xs,
          secondValues = reads,
          marker = Marker(
          ),
          mode = ScatterMode(Markers),
          hoverinfo = HoverInfo.Text,
          text = texts,
          name = id
        )
    }
    val plotData = traces.toSeq
    val layout = Layout(
      title = s"",
      xaxis = Axis(
        title = s"Length(bp)",
        `type` = AxisType.Linear,
        tickangle = 0.0,
        autorange = true,
        tickfont = Font(size = 10)
      ),
      yaxis = Axis(
        title = s"Number of reads",
        autorange = true
      ),
      margin = Margin(b = 40, l = 80, t = 0, r = 0),
      hovermode = Closest,
      width = 700,
      height = 500,
      dragmode = false,
      legend = Legend(
        xanchor = Anchor.Right,
        x = 1.0,
        y = 1.0
      )
    )
    val config = PlotlyConfigOptions.displayModeBar(false)
    myPlotly.newPlot(jq, plotData, layout, config)
  }

  def vennPlot(array: JArJDJAn, jq: JQuery) = {
    val trace1 = Scatter(
      values = Seq(1, 1.75, 2.5),
      secondValues = Seq(1, 1, 1),
      mode = ScatterMode(Text),
      text = Seq("Test-1<br>17", "Intersect<br>5", "Test-2<br>16"),
      textfont = TextFont(
        color = new StringColor("black"),
        size = 18.0,
        family = "Arial"
      ),
      hoverinfo = HoverInfo.Text,
    )
    val layout = Layout(
      title = s"Venn Diagram with Circle Shapes",
      xaxis = Axis(
        showticklabels = false,
        autotick = false,
        showgrid = false,
        zeroline = false
      ),
      yaxis = Axis(
        showticklabels = false,
        autotick = false,
        showgrid = false,
        zeroline = false
      ),
      shapes = Seq(
        Shape(
          opacity = 0.3,
          xref = XRef,
          yref = YRef,
          fillcolor = new StringColor("blue"),
          x0 = 0,
          y0 = 0,
          x1 = 2,
          y1 = 2,
          `type` = "circle",
          line = Line(
            color = new StringColor("blue")
          )
        ),
        Shape(
          opacity = 0.3,
          xref = XRef,
          yref = YRef,
          fillcolor = new StringColor("gray"),
          x0 = 1.2,
          y0 = 0,
          x1 = 3.2,
          y1 = 2,
          `type` = "circle",
          line = Line(
            color = new StringColor("gray")
          )
        ),
      ),
      margin = Margin(b = 100, l = 20, t = 40, r = 20),
      width = 480,
      height = 400,
      dragmode = false,
      hovermode = Closest,
    )
    val config = PlotlyConfigOptions.displayModeBar(false)
    myPlotly.newPlot(jq, Seq(trace1), layout, config)
  }

  def getId = {
    g.id.toString
  }

  def refreshMissionInfo(id: String) = {
    val url = g.jsRoutes.controllers.SampleController.getMissionInfoById().url.toString
    Ajax.get(url = s"${
      url
    }?missionId=${
      id
    }").map {
      xhr =>
        val dict = JSON.parse(xhr.responseText).toJDS
        dict.foreach {
          case (k, v) =>
            $(s"#mission #${
              k
            }").text(v.toString)
        }
    }
  }


}
